from fastapi import APIRouter, Depends, Query, Path

from src.base.beans import Rest
from src.config.auth import auth_depend
from src.config.db import DbSession
from src.config.log import log_depend
from src.dao.sys_role_dao import get_role_by_id, get_role_list_by_condition, get_role_page_by_condition, insert_role, \
    update_role, delete_roles, get_role_list_by_ids, get_role_menu_mapping_list_by_ids
from src.domain.sys_role import SysRoleReq, SysRole

router = APIRouter(prefix='/sys/role', dependencies=[Depends(auth_depend), Depends(log_depend)], tags=["角色管理"])


@router.get("/get_by_id/{id}", summary="根据ID查询", )
async def get_by_id(dbSession: DbSession, id: str = Path()):
    dept = await get_role_by_id(dbSession, int(id))
    return Rest.ok(dept)


@router.get("/get_by_ids", summary="根据ID集合查询", )
async def get_by_ids(dbSession: DbSession, ids: list[str] = Query()):
    dept = await get_role_list_by_ids(dbSession, [int(id) for id in ids])
    return Rest.ok(dept)


@router.get("/list", summary="根据条件查询用户列表", )
async def get_list_by_condition(dbSession: DbSession, entity: SysRoleReq = Query(default=None)):
    roles = await get_role_list_by_condition(dbSession, entity)
    role_menu = await get_role_menu_mapping_list_by_ids(dbSession, [role.role_id for role in roles])
    for role in roles:
        role.menu_ids = [rm.menu_id for rm in role_menu if rm.role_id == role.role_id] if role_menu else []
    return Rest.ok(roles)


@router.get("/page", summary="根据条件分页查询用户列表", )
async def get_page_by_condition(dbSession: DbSession, entity: SysRoleReq = Query(default=None)):
    page_result = await get_role_page_by_condition(dbSession, entity)
    role_menu = await get_role_menu_mapping_list_by_ids(dbSession, [role.role_id for role in page_result.data])
    for role in page_result.data:
        role.menu_ids = [rm.menu_id for rm in role_menu if rm.role_id == role.role_id] if role_menu else []
    return Rest.ok(page_result)


@router.post("/create", summary="新增", )
async def create(dbSession: DbSession, entity: SysRoleReq):
    await insert_role(dbSession, entity)
    return Rest.ok()


@router.put("/edit", summary="修改", )
async def edit(dbSession: DbSession, entity: SysRoleReq):
    result = await update_role(dbSession, entity)
    return Rest.ok() if result > 0 else Rest.fail()


@router.post("/create_edit", summary="新增或修改", )
async def create_edit(dbSession: DbSession, entity: SysRoleReq):
    result = 1
    if entity.role_id is None:
        await insert_role(dbSession, entity)
    else:
        result = await update_role(dbSession, entity)
    return Rest.ok() if result > 0 else Rest.fail()


@router.delete("/delete", summary="删除", )
async def delete(dbSession: DbSession, ids: list[str] = Query()):
    result = await delete_roles(dbSession, [int(id) for id in ids])
    return Rest.ok() if result > 0 else Rest.fail()
